package com.example.aiscripteditorserver.controller;


import com.example.aiscripteditorserver.common.AjaxResult;
import com.example.aiscripteditorserver.common.tools.match.ImgMatcherUtils;
import com.example.aiscripteditorserver.common.tools.match.MatchResult;
import com.example.aiscripteditorserver.services.ImageProcessingService;
import lombok.extern.slf4j.Slf4j;
import org.opencv.core.Mat;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;

@Slf4j
@RestController
@RequestMapping("/img_match")
public class ImgMatchController {

    @Resource
    private ImageProcessingService imageProcessingService;
    
    @PostMapping("/ac")
    public AjaxResult imgMatch(
            @RequestParam("template") MultipartFile small,
            @RequestParam("source") MultipartFile big){


        if (small.isEmpty() || big.isEmpty()) {
            return AjaxResult.error("文件为空");
        }

        try {
            // 调用Service层方法将上传的文件转换为Mat
            Mat smallImg = imageProcessingService.convertMultipartFileToMat(small);
            Mat bigImg = imageProcessingService.convertMultipartFileToMat(big);

            if (smallImg == null && bigImg == null) {
                return AjaxResult.error("文件转换为图像失败");
            }

            String saveResultPath = ""; // 结果图片保存路径（生成的图片）
            double startScale = 0.5; // 最小缩放比例（50%）
            double endScale = 1.5;   // 最大缩放比例（150%）
            double step = 0.05;      // 缩放步长（步长越小精度越高，速度越慢）
            double threshold = 0.8; // 匹配度阈值（0~1，值越高匹配越严格）
            
            MatchResult res = ImgMatcherUtils.multiScaleMatch(bigImg, smallImg, saveResultPath,
                    startScale, endScale, step, threshold);

            String matchContent = small.getOriginalFilename()+"/"+big.getOriginalFilename();
            if (res == null) {
                log.info("匹配失败：" + matchContent);
            }
            return AjaxResult.success("成功！已尝试匹配：" + matchContent, res);

        } catch (IOException e) {
            log.error("图像匹配错误", e);
        }

        return AjaxResult.error("匹配失败");


    }


}
